// 多媒体预览组件 - 支持图片、视频、音乐预览
(function() {
    if (typeof Vue === 'undefined') {
        console.error('Vue is not loaded');
        return;
    }
    
    const { ref, computed, onMounted, onUnmounted, watch } = Vue;

    const MultiMediaPreview = {
        name: 'MultiMediaPreview',
        template: `
            <div v-if="visible" class="media-preview-overlay" @click="handleOverlayClick">
                <div class="media-preview-container" @click.stop>
                    <!-- 左侧切换按钮 -->
                    <button v-if="canGoPrev" @click="prevFile" class="nav-btn prev-btn">
                        <span>‹</span>
                    </button>
                    
                    <!-- 右侧切换按钮 -->
                    <button v-if="canGoNext" @click="nextFile" class="nav-btn next-btn">
                        <span>›</span>
                    </button>
                    
                    <!-- 顶部控制栏 -->
                    <div class="media-preview-header">
                        <div class="media-preview-title">{{ currentFile.file_name }}</div>
                        <div class="media-preview-controls">
                            <button @click="closePreview" class="control-btn close-btn">×</button>
                        </div>
                    </div>
                    
                    <!-- 预览内容区域 -->
                    <div class="media-preview-content" ref="contentRef">
                        <!-- 图片预览 -->
                        <div v-if="isImage" class="image-preview">
                            <div class="image-container" 
                                 @wheel="handleWheel"
                                 @mousedown="handleMouseDown"
                                 :style="{ cursor: isDragging ? 'grabbing' : (scale > 1 ? 'grab' : 'default') }">
                                <img :src="currentFile.cover" 
                                     :alt="currentFile.file_name" 
                                     :style="imageStyle"
                                     @load="handleImageLoad"
                                     @dragstart.prevent
                                     ref="imageRef" />
                                <!-- 图片内部控制栏 -->
                                <div class="image-controls-overlay">
                                    <button @click="zoomOut" :disabled="scale <= 0.1" class="zoom-btn-overlay">-</button>
                                    <span class="zoom-info-overlay">{{ Math.round(scale * 100) }}%</span>
                                    <button @click="zoomIn" :disabled="scale >= 5" class="zoom-btn-overlay">+</button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 视频预览 -->
                        <div v-else-if="isVideo" class="video-preview">
                            <video :src="getMediaUrl(currentFile)" 
                                   controls 
                                   preload="metadata"
                                   @loadedmetadata="handleVideoLoad"
                                   @error="handleVideoError"
                                   ref="videoRef">
                                您的浏览器不支持视频播放
                            </video>
                            <div v-if="videoError" class="error-message">
                                视频加载失败：{{ videoError }}
                            </div>
                            <div v-else class="video-info">
                                文件大小：{{ currentFile.size }}
                            </div>
                        </div>
                        
                        <!-- 音频预览 -->
                        <div v-else-if="isAudio" class="audio-preview">
                            <div class="audio-info">
                                <div class="audio-icon">🎵</div>
                                <div class="audio-name">{{ currentFile.file_name }}</div>
                                <div class="audio-size">文件大小：{{ currentFile.size }}</div>
                                <div v-if="audioDuration" class="audio-duration">时长: {{ formatTime(audioDuration) }}</div>
                            </div>
                            <audio :src="getMediaUrl(currentFile)" 
                                   controls 
                                   preload="metadata"
                                   @loadedmetadata="handleAudioLoad"
                                   @error="handleAudioError"
                                   ref="audioRef">
                                您的浏览器不支持音频播放
                            </audio>
                            <div v-if="audioError" class="error-message">
                                音频加载失败：{{ audioError }}
                            </div>
                        </div>
                        
                        <!-- 不支持的文件类型 -->
                        <div v-else class="unsupported-preview">
                            <div class="unsupported-icon">📄</div>
                            <div class="unsupported-text">暂不支持预览此文件类型</div>
                            <div class="file-info">{{ currentFile.file_name }}</div>
                        </div>
                    </div>
                </div>
            </div>
        `,
        props: {
            visible: Boolean,
            files: Array,
            currentIndex: Number
        },
        emits: ['update:visible', 'update:currentIndex'],
        setup(props, { emit }) {
            // 响应式数据
            const scale = ref(1);
            const translateX = ref(0);
            const translateY = ref(0);
            const isDragging = ref(false);
            const dragStart = ref({ x: 0, y: 0 });
            const imageLoaded = ref(false);
            
            // 媒体状态
            const audioDuration = ref(0);
            const videoError = ref('');
            const audioError = ref('');
            
            // DOM引用
            const contentRef = ref(null);
            const imageRef = ref(null);
            const videoRef = ref(null);
            const audioRef = ref(null);
            
            // 计算属性
            const currentFile = computed(() => {
                return props.files[props.currentIndex] || {};
            });
            
            const isImage = computed(() => {
                return currentFile.value.type === 1;
            });
            
            const isVideo = computed(() => {
                return currentFile.value.type === 7;
            });
            
            const isAudio = computed(() => {
                return currentFile.value.type === 6;
            });
            
            const canGoPrev = computed(() => {
                return props.currentIndex > 0;
            });
            
            const canGoNext = computed(() => {
                return props.currentIndex < props.files.length - 1;
            });
            
            const imageStyle = computed(() => {
                return {
                    transform: `scale(${scale.value}) translate(${translateX.value}px, ${translateY.value}px)`,
                    transition: isDragging.value ? 'none' : 'transform 0.3s ease',
                    transformOrigin: 'center center'
                };
            });
            
            // 方法
            const getMediaUrl = (file) => {
                // 优先使用后端返回的url字段
                if (file.url) {
                    return file.url;
                }
                
                // 如果没有url字段，对于图片使用cover字段
                if (file.type === 1 && file.cover) {
                    return file.cover;
                }
                
                // 兜底：使用API管理器构建下载URL
                if (file.id && window.API) {
                    return window.API.files.getDownloadUrl(file.id);
                }
                
                return file.cover || '';
            };
            
            const formatTime = (seconds) => {
                const minutes = Math.floor(seconds / 60);
                const secs = Math.floor(seconds % 60);
                return `${minutes}:${secs.toString().padStart(2, '0')}`;
            };
            const closePreview = () => {
                emit('update:visible', false);
            };
            
            const prevFile = () => {
                if (canGoPrev.value) {
                    emit('update:currentIndex', props.currentIndex - 1);
                }
            };
            
            const nextFile = () => {
                if (canGoNext.value) {
                    emit('update:currentIndex', props.currentIndex + 1);
                }
            };
            
            const handleOverlayClick = (e) => {
                if (e.target === e.currentTarget) {
                    closePreview();
                }
            };
            
            // 图片缩放功能
            const zoomIn = () => {
                if (scale.value < 5) {
                    scale.value = Math.min(5, scale.value * 1.2);
                }
            };
            
            const zoomOut = () => {
                if (scale.value > 0.1) {
                    scale.value = Math.max(0.1, scale.value / 1.2);
                    if (scale.value <= 1) {
                        translateX.value = 0;
                        translateY.value = 0;
                    }
                }
            };

            
            // 滚轮缩放
            const handleWheel = (e) => {
                if (!isImage.value || !imageLoaded.value) return;
                
                e.preventDefault();
                const delta = e.deltaY > 0 ? -1 : 1;
                const zoomFactor = 1 + (delta * 0.1);
                const newScale = Math.min(5, Math.max(0.1, scale.value * zoomFactor));
                
                if (newScale !== scale.value) {
                    scale.value = newScale;
                    if (scale.value <= 1) {
                        translateX.value = 0;
                        translateY.value = 0;
                    }
                }
            };
            
            // 鼠标拖拽
            const handleMouseDown = (e) => {
                if (!isImage.value || scale.value <= 1) return;
                
                e.preventDefault();
                isDragging.value = true;
                dragStart.value = {
                    x: e.clientX - translateX.value,
                    y: e.clientY - translateY.value
                };
                
                document.addEventListener('mousemove', handleMouseMove);
                document.addEventListener('mouseup', handleMouseUp);
            };
            
            const handleMouseMove = (e) => {
                if (!isDragging.value) return;
                
                translateX.value = e.clientX - dragStart.value.x;
                translateY.value = e.clientY - dragStart.value.y;
            };
            
            const handleMouseUp = () => {
                isDragging.value = false;
                document.removeEventListener('mousemove', handleMouseMove);
                document.removeEventListener('mouseup', handleMouseUp);
            };
            
            // 媒体加载事件
            const handleImageLoad = () => {
                imageLoaded.value = true;
            };
            
            const handleVideoLoad = () => {
                videoError.value = '';
                console.log('Video loaded successfully');
            };
            
            const handleVideoError = (e) => {
                videoError.value = '无法加载视频文件，请检查文件路径或格式';
                console.error('Video error:', e);
            };
            
            const handleAudioLoad = (e) => {
                audioError.value = '';
                audioDuration.value = e.target.duration || 0;
                console.log('Audio loaded, duration:', audioDuration.value);
            };
            
            const handleAudioError = (e) => {
                audioError.value = '无法加载音频文件，请检查文件路径或格式';
                console.error('Audio error:', e);
            };
            
            // 监听文件切换，重置状态
            watch(() => props.currentIndex, () => {
                videoError.value = '';
                audioError.value = '';
                audioDuration.value = 0;
            });
            
            // 键盘事件
            const handleKeyDown = (e) => {
                if (!props.visible) return;
                
                switch (e.key) {
                    case 'Escape':
                        closePreview();
                        break;
                    case 'ArrowLeft':
                        prevFile();
                        break;
                    case 'ArrowRight':
                        nextFile();
                        break;
                }
            };
            
            // 生命周期
            onMounted(() => {
                document.addEventListener('keydown', handleKeyDown);
            });
            
            onUnmounted(() => {
                document.removeEventListener('keydown', handleKeyDown);
            });
            
            return {
                // 数据
                scale,
                translateX,
                translateY,
                isDragging,
                imageLoaded,
                audioDuration,
                videoError,
                audioError,
                
                // 引用
                contentRef,
                imageRef,
                videoRef,
                audioRef,
                
                // 计算属性
                currentFile,
                isImage,
                isVideo,
                isAudio,
                canGoPrev,
                canGoNext,
                imageStyle,
                
                // 方法
                getMediaUrl,
                formatTime,
                closePreview,
                prevFile,
                nextFile,
                handleOverlayClick,
                
                // 缩放功能
                zoomIn,
                zoomOut,
                handleWheel,
                handleMouseDown,
                
                // 媒体加载
                handleImageLoad,
                handleVideoLoad,
                handleVideoError,
                handleAudioLoad,
                handleAudioError
            };
        }
    };

    // 导出组件
    window.MultiMediaPreview = MultiMediaPreview;
    
})();